package com.example.agrigreennewssys.service.impl;

import com.example.agrigreennewssys.dao.TagMapper;
import com.example.agrigreennewssys.entity.Tag;
import com.example.agrigreennewssys.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service("tagService")
public class TagServiceImpl implements TagService {
    @Autowired
    private TagMapper tagMapper;

    @Override
    public Tag createTag(Tag tag) {
        // 检查标签名称是否已存在
        Tag existingTag = tagMapper.selectTagByName(tag.getName());
        if (existingTag != null) {
            throw new RuntimeException("标签名称已存在");
        }
        tag.setCreatedAt(String.valueOf(new Date()));
        tag.setUpdatedAt(String.valueOf(new Date()));

        tagMapper.insertTag(tag);
        return tag;
    }

    @Override
    public Tag updateTag(Tag tag) {
        // 验证标签是否存在
        Tag existingTag = tagMapper.selectTagById(tag.getId());
        if (existingTag == null) {
            throw new RuntimeException("标签不存在");
        }

        // 检查标签名称是否已存在（排除自身）
        Tag sameNameTag = tagMapper.selectTagByName(tag.getName());
        if (sameNameTag != null && !sameNameTag.getId().equals(tag.getId())) {
            throw new RuntimeException("标签名称已存在");
        }

        tag.setUpdatedAt(String.valueOf(new Date()));
        tagMapper.updateTag(tag);
        return tagMapper.selectTagById(tag.getId());
    }

    @Override
    public boolean deleteTag(Long id) {
        Tag tag = tagMapper.selectTagById(id);
        if (tag == null) {
            return false;
        }

        // 删除关联的文章标签（根据外键约束自动处理）
        tagMapper.deleteTagById(id);
        return true;
    }

    @Override
    public Tag getTagById(Long id) {
        return tagMapper.selectTagById(id);
    }

    @Override
    public List<Tag> getAllTags() {
        return tagMapper.selectAllTags();
    }

}
